package com.jmu.bishe.service.main;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *<pre><b><font color="blue">TableService</font></b></pre>
 *
 *<pre><b>&nbsp;--操作数据库的类--</b></pre>
 * JDK版本：JDK1.5.0
 * @author  <b>ulyn</b> 
 */
@Service
@Transactional
public class TableService {
	
	private static Logger logger = Logger.getLogger(TableService.class);

	private JdbcTemplate jdbcTemplate;
	
	@Resource(name = "jdbcTemplate")
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

    /**
     * 获取数据-根据sql和页码条件
     * @param sql 查询的sql
     * @param params 参数
     * @param currentPage 当前第几页，值为0时候取第一页
     * @param linePerPage 每页几条记录，值为0时候取10条记录
     * @return
     */
    public List queryForList(String sql,List params,int currentPage,int linePerPage){
        if(currentPage==0){
            currentPage = 1;
        }
        if(linePerPage==0){
            currentPage = 10;
        }
        int begin=(currentPage-1)*linePerPage;
        int end=currentPage*linePerPage-1;
        /*int totalNum = getTotalNumber(sql,tjs);
        if(end+1>totalNum){
            end = totalNum-1;
        }*/
        sql = "SELECT * FROM(SELECT A.*, ROWNUM RN FROM(" + sql + ") A WHERE ROWNUM <= " + (end+1) + ")WHERE RN >= " + (begin+1);
        logger.info("查询列表:"+sql);
        logger.info("参数列表:" + params);
        List list = jdbcTemplate.queryForList(sql,params.toArray());
       // list= XfListUtils.standardList(list);
        return list;
    }
	public int getTotalNumber(String sql,List tjs){
        if(sql.toLowerCase().indexOf("group")!=-1){
            sql = "select count(*) from ("+sql+")";
        }else{
            sql = "select count(*) s " + sql.substring(sql.toLowerCase().lastIndexOf("from"));
        }
        logger.info("获取sql的总记录数:"+sql);
        int result = jdbcTemplate.queryForInt(sql,tjs.toArray());
        logger.info("获取sql的总记录数:"+result);
        return result;
    }
	
}
